package com.etop.jansing.service;

import com.etop.jansing.dao.PermissionDao;
import com.etop.jansing.dao.ResourceDao;
import com.etop.jansing.dao.ResourcePermissionDao;
import com.etop.jansing.dto.ResourceDto;
import com.etop.jansing.entities.Permission;
import com.etop.jansing.entities.Resource;
import com.etop.jansing.entities.ResourcePermission;
import com.etop.jansing.entities.Role;
import com.etop.jansing.util.CommonUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


/**
 * Created by jansing on 2015/10/25.
 */
@Service
public class ResourceService extends BaseService{
    @javax.annotation.Resource
    private ResourceDao resourceDao;
    @javax.annotation.Resource
    private PermissionDao permissionDao;
    @javax.annotation.Resource
    private ResourcePermissionDao resourcePermissionDao;

    public Resource getById(long id) {
        log.info("-->获取id=["+id+"]的资源");
        Resource resource = resourceDao.get(id);
        if(resource==null) {
            log.warn("-->id=[" + id + "]的资源不存在");
        }
        return resource;
    }

    /**
     * 排除root资源
     * @return
     */
    public List<Resource> getAllResources() {
        log.info("-->获取所有资源");
        List<Resource> list = resourceDao.list();
        return list;
    }

    public ResourceDto getRootResource(Collection<Role> roles) {
        log.info("-->获取root资源及其下子资源，并且转成DTO返回");
        //解决延迟加载问题，一次性把所有资源权限对、资源、权限取出
        List<Resource> allResources = getAllResources();
        List<ResourcePermission> resourcePermissionList = null;
        if(roles!=null&&roles.size()>0) {
            resourcePermissionList = resourcePermissionDao.getResoPermListByRoles(CommonUtils.getIds(roles));
        }else{

        }
        List<Permission> permissionList = permissionDao.list();
        for(Resource resource : allResources){
            if(resource.getParent()==null){
                 return CommonUtils.getResourceDto(resource, resourcePermissionList);
            }
        }
        log.warn("-->没有root资源！");
        return null;
    }

    public List<Resource> getCanBeParentResources(Resource currentResource) {
        log.info("-->获取所有可作为父资源的资源，但排除它自己");
        List<Resource> tempList = CommonUtils.getCanBeParent(resourceDao.list());
        tempList.remove(currentResource);
        return tempList;
    }

    /**
     * 获取所有可赋予权限的资源，也就是叶子资源
     * @return
     */
    public List<Resource> getCanGetPermission(){
        return resourceDao.getLeafResourceList();
    }

    public Resource getByNameIgnoreValid(String name) {
        log.info("-->获取name=["+name+"]的资源");
        Resource resource = resourceDao.getByNameIgnoreValid(name);
        if(resource==null) {
            log.warn("-->name=[" + name + "]的资源不存在");
        }
        return resource;
    }

    /**
     * 保存或更新资源
     *
     * @param resource
     * @param pids
     */
    public void saveOrUpdate(Resource resource,Long parentId, String[] pids) {
        Resource parent = resourceDao.get(parentId);
        if (resource.getId() != null && resource.getId() > 0) {
            if(resource.getParent()==null||resource.getParent().getId()!=parentId){
                resource.setParent(parent);
            }
            log.info("-->更新资源");
            resourceDao.update(resource);
        } else {
            log.info("-->保存资源");
            resource.setParent(parent);
            resourceDao.save(resource);
        }

        List<Long> tempPids = CommonUtils.parseIds(pids);
        List<Permission> newPermissionList;
        if (tempPids == null || tempPids.size() == 0) {
            newPermissionList = new ArrayList<>();
        } else {
            newPermissionList = permissionDao.getByIds(tempPids);
        }
        List<ResourcePermission> deleteResourcePermission = new ArrayList<>();
        for (ResourcePermission rp : resource.getResourcePermissionList()) {
            if (newPermissionList.contains(rp.getPermission())) {
                //两者共同拥有的就不处理
                newPermissionList.remove(rp.getPermission());
            } else {
                deleteResourcePermission.add(rp);
            }
        }
        //删除
        if (!deleteResourcePermission.isEmpty()) {
            resource.getResourcePermissionList().removeAll(deleteResourcePermission);
            resourcePermissionDao.deleteResourcePermission(CommonUtils.getIds(deleteResourcePermission));
        }
        //增加
        List<ResourcePermission> addResourcePermissionList = new ArrayList<>();
        for (Permission p : newPermissionList) {
            ResourcePermission newResourcePermission = new ResourcePermission(resource, p);
            resourcePermissionDao.save(newResourcePermission);
            addResourcePermissionList.add(newResourcePermission);
        }
        resource.getResourcePermissionList().addAll(addResourcePermissionList);
    }

    /**
     * 是否有某个角色拥有该资源的某个权限
     *
     * @param resource
     * @return
     */
    public boolean isUsing(Resource resource) {
        if (resourceDao.isUsing(resource) > 0) {
            log.info("-->id=[" + resource.getId() + "]的资源正被使用");
            return true;
        }
        log.info("-->id=[" + resource.getId() + "]的资源没有被使用");
        return false;
    }

    /**
     * 删除资源前，先将资源权限对删掉
     *
     * @param resource
     */
    public void delete(Resource resource) {
        log.info("-->删除id=["+resource.getId()+"]的资源");
        resourcePermissionDao.deleteResourcePermission(resource);
        resource.getResourcePermissionList().clear();
        resource.setParent(null);
        resourceDao.delete(resource);
    }
}
